//
//  PCDApiKeyBoard.m
//  PCDBankSix
//
//  Created by DK on 2022/3/4.
//

#import "PCDApiKeyBoard.h"

#import <YTKeyboard/YTKeyboard.h>
#import <PCDH5Container/PCDH5Container.h>

#import "PCDBankWebViewController.h"
#import "PCDKeyBoardManage.h"
#import "shahaiKeyBoard.h"

#define  KBoardTtitle @"河北银行安全键盘"

//键盘震动开关
#define SETTING_KEYBOARD_SHARKCLOSE @"keyboardSharkClose"
//键盘声音开关
#define SETTING_KEYBOARD_VoiceCLOSE @"keyboardVoiceClose"

@interface PCDApiKeyBoard()<YTKeyboardViewDelegate, UITextFieldDelegate>{
    
    BOOL _keyboardIsShow;
}

@property (nonatomic,strong) PCDBankWebViewController *currentWebContainer;
@property (nonatomic,strong) YTKeyboardView *customKeyBoard;
@property (nonatomic,strong) shahaiKeyBoard *shahaiKeyBoard;
@property (nonatomic,strong) UIControl *viewSheet;
@property (nonatomic,strong) NSString *shaHaicallBackName;
@property (nonatomic,strong) UITextField *inputfield;

@end

@implementation PCDApiKeyBoard


- (void)handler:(id)data andContext:(PCDContext *)context ResponseCallback:(WVJBResponseCallback )responseCallback
{
    NSDictionary *dict = (NSDictionary *)data;
    
    self.bsContext = context;
    
    YTKeyboardType t = -100;
    KeyBoardType shahaiType = 0;
    
    PCDBankWebViewController *bankWebView =(PCDBankWebViewController *) context.viewController;
    self.currentWebContainer = bankWebView;
    
    __weak typeof(self) tempSelf = self;
    [bankWebView setBackBlock:^(BOOL status) {
        if (status) {
            [tempSelf hideKeyBoard];
        }
    }];
    
    NSString *func = [dict objectForKey:@"success"];
    
    NSString *type = [dict objectForKey:@"type"];
    if ([@"MONEY" isEqualToString:type]) {
        //金额键盘
        t = YTKeyboardTypeMoney;
        [self getTrueKeyBoary:data type:t func:func];
    }else if ([@"TPWD" isEqualToString:type]){
        //交易密码键盘
        [self getShahaiKeyBoary:data type:KeyBoardTypeNumber func:func];
    }else if ([@"LPWD" isEqualToString:type]){
        //登录密码键盘
        [self getShahaiKeyBoary:data type:KeyBoardTypeNone func:func];
    }else if ([@"IDC" isEqualToString:type]){
        //身份证键盘
        t = YTKeyboardTypeIDCard;
        [self getTrueKeyBoary:data type:t func:func];
    }else if ([@"NUMBER" isEqualToString:type]){
        //数字键盘
        t = YTKeyboardTypeOnlyNumber;
        [self getTrueKeyBoary:data type:t func:func];
    }else if ([@"QWER" isEqualToString:type]){
        //全键盘
        t = YTKeyboardTypeLetterWithNumber;
        [self getTrueKeyBoary:data type:t func:func];
    }else {
        //待验证
        [self hideKeyBoard];
        
        return;
    }
    
    
}

- (void)getTrueKeyBoary:(id)data type:(YTKeyboardType)keyBoardType func:(NSString*)func{
    
    WKWebView *tmpWeb =  self.bsContext.webView;
    
    NSDictionary *dic;
    if ([data isKindOfClass:[NSDictionary class]]) {
        dic = (NSDictionary*)data;
    }else{
        dic =(NSDictionary*)[data JSONValue];
    }
    NSString*len=[dic objectForKey:@"len"];
    int lengthNum=[len intValue];
    
    if (self.customKeyBoard == nil) {
        
        self.customKeyBoard = [[YTKeyboardView alloc] initWithKeyboardType:keyBoardType];
        
        self.customKeyBoard.inputAccessoryView = [self inputAccessoryView];
        self.customKeyBoard.delegate = self;
    }else{
        [self.customKeyBoard clearData];
    }
        
    if (keyBoardType==YTKeyboardTypeMoney) {
        self.customKeyBoard.integerLength=lengthNum;
    }else{
        self.customKeyBoard.length=lengthNum;
    }
    
    NSString *type = [dic objectForKey:@"type"];
    if ([@"TPWD" isEqualToString:type]) {
        self.customKeyBoard.encrypt=YES;
    }
    
    if (keyBoardType==YTKeyboardTypeLetter) {
        self.customKeyBoard.encrypt=YES;
    }
    
    _viewSheet = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, tmpWeb.frame.size.width, tmpWeb.frame.size.height-self.customKeyBoard.frame.size.height)];
    [_viewSheet addTarget:self action:@selector(hideKeyBoard) forControlEvents:UIControlEventTouchUpInside];
    _viewSheet.backgroundColor = [UIColor clearColor];//背景色
    _viewSheet.alpha =0.3;
    [tmpWeb addSubview:_viewSheet];
    
    //赋值，用于在页面消失时关闭键盘
    self.currentWebContainer.controlSheet = _viewSheet;
    self.currentWebContainer.customKeyBoard = self.customKeyBoard;
    
    //第一次生成盐值
    __weak typeof(self) tempSelf = self;
    self.customKeyBoard.keyClickBlock = ^(NSInteger length, NSString *value) {
        
        NSString *strValue =[value stringByReplacingOccurrencesOfString:@"," withString:@""];
        //加密键盘
        NSString*scPass=strValue;
        NSString *password =strValue;//encrypt:passWord
        NSString *strSMPass = strValue;
         
        if (tempSelf.customKeyBoard.encrypt) {

            password = @"";
            NSArray *pwdArray =[value componentsSeparatedByString:@","];
            for (NSString *str in pwdArray) {
                NSString *decryptedString = [tempSelf.customKeyBoard.encryptTool decryptStr:str];
                password = [NSString stringWithFormat:@"%@%@",password,decryptedString];
            }
            
            //加密键盘
            scPass = @"";
            for (int i=0; i<length; i++) {
                scPass=[scPass stringByAppendingString:@"*"];
            }
            strSMPass = [[PCDEncrypt sharedEncrypt] sm2EncryptString:password];
        }

        //生成MD5
        NSString *str = [PCDDevice uniqueIdentifier];
        NSString *passMd5 = [[NSString stringWithFormat:@"%@%@",password,str] md5UpString];
      
        NSDictionary *dicData = @{@"showVal":scPass,@"passVal":strSMPass,@"passMd5":passMd5};
        evaluateJavaScriptOnMainThread(tempSelf, [dic objectForKey:@"success"],[dicData JSONRepresentation]);
        
        str = nil;
    };
    [self.customKeyBoard show];
    [self.customKeyBoard reload];
    
    NSDictionary *keyDic = @{KeyBoardDATA:_customKeyBoard,ViewSheetDATA:_viewSheet};
    [[PCDKeyBoardManage shareInstance].keyBoardList addObject:keyDic ];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self->_keyboardIsShow = YES;
    });
}


- (void)getShahaiKeyBoary:(id)data type:(KeyBoardType)keyBoardType func:(NSString*)func{
    
    WKWebView *tmpWeb =  self.bsContext.webView;
    
    NSDictionary *dic;
    if ([data isKindOfClass:[NSDictionary class]]) {
        dic = (NSDictionary*)data;
    }else{
        dic =(NSDictionary*)[data JSONValue];
    }
    __weak typeof(self) weakSelf = self;
    self.shaHaicallBackName = [dic objectForKey:@"success"];
    BOOL isVibrate = [dic objectForKey:@"isVibrate"];
    BOOL isSound = [dic objectForKey:@"isSound"];
    NSString*len=[dic objectForKey:@"len"];
    int lengthNum=[len intValue];
    
    if (self.shahaiKeyBoard == nil) {
        _shahaiKeyBoard=[[shahaiKeyBoard alloc]init];
        
        
        _shahaiKeyBoard.development = 1;
        _shahaiKeyBoard.showType=showLetter;
        _shahaiKeyBoard.keyboardtyp=keyBoardType;
        _shahaiKeyBoard.randomLetter=0;
        _shahaiKeyBoard.randomNumber=0;
        _shahaiKeyBoard.randomSpecial=0;
        _shahaiKeyBoard.maxLen=lengthNum;
        _shahaiKeyBoard.minLen=8;
        _shahaiKeyBoard.encrypt=0;
        _shahaiKeyBoard.needHighlighted=1;
        _shahaiKeyBoard.needShock= 0;
        _shahaiKeyBoard.needSound= 0; //先设置参数，然后再初始化沙海海键盘⽅方法 如果不不设置为默认BOOl=0
        if (isVibrate) {
            _shahaiKeyBoard.needShock= 1;
        }
        if (isSound) {
            _shahaiKeyBoard.needSound= 1; //先设置参数，然后再初始化沙海海键盘⽅方法 如果不不设置为默认BOOl=0
        }
        _shahaiKeyBoard.needScreenShotsAlert=1;
        _shahaiKeyBoard.needScreenRecordAlert=1;
//        _shahaiKeyBoard.needSpeechBroadcast = 1;

        
        //先设置参数，然后再初始化沙海键盘方法 如果不设置为默认BOOl=0
        [_shahaiKeyBoard initShahaiInputviewKeyboard];
        
    }
        //输入回调 如果加密传回为* 不加密传回原文
        [_shahaiKeyBoard.inputKeyboardView cilck:^(NSInteger length, NSString *value) {
            weakSelf.inputfield.text=value;
            NSString *strJson = @"";
            NSDictionary*backData=@{@"showVal":value,@"passVal":value,@"passMd5":value,@"showClear":@(value.length)};
            
            //                NSDictionary *backData  = @{@"data-value":value,@"data-passMd5":@"",@"data-xing":value};
            strJson = [backData JSONRepresentation];
            evaluateJavaScriptOnMainThread(self, [dic objectForKey:@"success"], strJson);
            //输入6位默认关闭键盘（交易密码键盘）
            if (keyBoardType == KeyBoardTypeNumber && value.length==6) {
                [self hideKeyBoard];
            }
        }];
        
        //点击删除回调 length=0为长安清空 1为单个删除
        [ _shahaiKeyBoard.inputKeyboardView cancle:^(NSInteger length, NSString *value) {
            if (length==0) {
                weakSelf.inputfield.text=@"";
                NSString *strJson = @"";
                NSDictionary*backData=@{@"showVal":value,@"passVal":value,@"passMd5":value,@"showClear":@(value.length)};

//                NSDictionary *backData  = @{@"data-value":value,@"data-passMd5":@"",@"data-xing":value};
                strJson = [backData JSONRepresentation];
                evaluateJavaScriptOnMainThread(self, [dic objectForKey:@"success"], strJson);
            }
            else{
                weakSelf.inputfield.text=[weakSelf.inputfield.text substringToIndex:length];
                NSDictionary*backData=@{@"showVal":value,@"passVal":value,@"passMd5":value,@"showClear":@(value.length)};
                NSString *strJson = @"";
                strJson = [backData JSONRepresentation];
                evaluateJavaScriptOnMainThread(self, [dic objectForKey:@"success"], strJson);
            }
        }];
        
        //点击确定回调 加密传回经过沙海加密库加密后的密文和原文长度，不加密传回原文和原文长度
        [_shahaiKeyBoard.inputKeyboardView returnKey:^(NSInteger length, NSString *value,NSString * pwdMD5) {
            if ([value isEqualToString:@"-4001"]) {
                NSString *strJson = @"";
                NSDictionary*backData=@{@"showVal":@"",@"passVal":@"",@"passMd5":@"", @"showClear":@""};
                strJson = [backData JSONRepresentation];
                evaluateJavaScriptOnMainThread(self, [dic objectForKey:@"success"], strJson);
            }else{
                NSString *strJson = @"";
//                NSDictionary *backData  = @{@"data-value":value,@"data-passMd5":pwdMD5,@"data-xing":self.inputfield.text};
                NSDictionary*backData=@{@"showVal":weakSelf.inputfield.text,@"passVal":value,@"passMd5":pwdMD5,@"showClear":@(length)};
                strJson = [backData JSONRepresentation];
                evaluateJavaScriptOnMainThread_quotes(self, [dic objectForKey:@"success"], strJson);
            }
            evaluateJavaScriptOnMainThread(self, @"_hideKeyboard", @"")

            [_inputfield resignFirstResponder];
            if (self.viewSheet) {
                [self.viewSheet removeFromSuperview];
            }
            
//            [self->_inputfield removeFromSuperview];
//            [self hideKeyBoard];
        }];
        
        _inputfield = [[UITextField alloc]initWithFrame:CGRectMake(80,80, 200, 29)];
        _inputfield.backgroundColor = [UIColor yellowColor];
        _inputfield.tag=10000;
        _inputfield.inputView = _shahaiKeyBoard.inputKeyboardView;
        _inputfield.borderStyle = UITextBorderStyleRoundedRect;
        _inputfield.secureTextEntry = YES;
        _inputfield.delegate=self;
    /**
     不明原因造成设置[IQKeyboardManager sharedManager].enableAutoToolbar = NO 对沙海键盘失效,
    查看IQKeyboardManager源码发现toolbar添加时机为inputAccessoryView = nil,添加以下代码防止toolbar弹出
     */
        _inputfield.inputAccessoryView = [UIView new];

    _viewSheet = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, tmpWeb.frame.size.width, tmpWeb.frame.size.height-_shahaiKeyBoard.inputKeyboardView.frame.size.height)];
    [_viewSheet addTarget:self action:@selector(hideKeyBoard) forControlEvents:UIControlEventTouchUpInside];
    _viewSheet.backgroundColor = [UIColor clearColor];//背景色
    _viewSheet.alpha =0.3;
    [tmpWeb addSubview:_viewSheet];
    [tmpWeb addSubview:_inputfield];
    [_shahaiKeyBoard addTextfield:_inputfield];
    [_inputfield becomeFirstResponder];
//    _inputfield.hidden = YES;
    
    [tmpWeb sendSubviewToBack:_inputfield];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self->_keyboardIsShow = YES;
    });
}


-(void)hideKeyBoard{
    if (_customKeyBoard) {
        [[PCDKeyBoardManage shareInstance] hideKeyBoard];
        evaluateJavaScriptOnMainThread(self, @"_hideKeyboard", @"")
    }
    if (_shahaiKeyBoard) {
        if (_keyboardIsShow == NO) return;
        [_shahaiKeyBoard dissMisskeyboard];
        self.shahaiKeyBoard =nil;
        [_viewSheet removeFromSuperview];
        //回调
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self->_keyboardIsShow = NO;
        });
        evaluateJavaScriptOnMainThread(self, @"_hideKeyboard", @"")
    }
}

-(UIView *)inputAccessoryView
{
    
    UILabel *inputAccessoryView = [[UILabel alloc] init];
    inputAccessoryView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 41);
    inputAccessoryView.backgroundColor = [YTKeyboardUtil getColor:[YTKeyboardUtil shareInstance].keyboardStyle == 0 ? @"#e8e8e8" : @"#212121"];
    inputAccessoryView.textColor = [YTKeyboardUtil getColor:[YTKeyboardUtil shareInstance].keyboardStyle == 0 ? @"#272727" : @"#929292"];
    inputAccessoryView.text = KBoardTtitle;
    inputAccessoryView.textAlignment = NSTextAlignmentCenter;
    
    return inputAccessoryView;
}

#pragma mark - 代理 YTKeyboardViewDelegate
/**
 键盘切换
 
 @param keyBoardView 键盘视图
 @param keyboardType 当前键盘类型
 @param section 区域编号
 @param indexPath 按键indexPath
 @return 要切换到的键盘类型
 */
- (YTKeyboardType)keyBoardView:(YTKeyboardView *)keyBoardView keyboardTypeFromKeyboardType:(YTKeyboardType)keyboardType section:(NSInteger)section indexPath:(YTIndexPath *)indexPath {
    
    if (keyboardType == YTKeyboardTypeNumber) {
        
        return YTKeyboardTypeLetter;
        
    }else if (keyboardType == YTKeyboardTypeLetter){
        
        return YTKeyboardTypeNumber;
    }
    
    return keyboardType;
}

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    NSDate *today = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter  alloc ]  init ];
    [formatter setDateFormat:@"yyyyMMddHHmmss"];
    formatter.locale = [NSLocale systemLocale];
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"GMT"];
    [formatter setTimeZone:timeZone];
    NSString * timeStr1 = [formatter stringFromDate:today];
        
    [_shahaiKeyBoard randomKeyBoard];
    _shahaiKeyBoard.inputKeyboardView.timeStr=timeStr1;
    _inputfield.text=@"";
    
    NSString *strJson = @"";
    NSDictionary*backData=@{@"showVal":@"",@"passVal":@"",@"passMd5":@""};
    strJson = [backData JSONRepresentation];
    evaluateJavaScriptOnMainThread_quotes(self, self.shaHaicallBackName, strJson);

//    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;//禁用键盘上的toolbar 也就是按钮
//    [IQKeyboardManager sharedManager].enable = NO;// 禁止键盘出现时的界面滚动

}

-(void)textFieldDidEndEditing:(UITextField *)textField{
//    evaluateJavaScriptOnMainThread(self, self.shaHaicallBackName, self.h5Json);
//    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;//禁用键盘上的toolbar 也就是按钮
//    [IQKeyboardManager sharedManager].enable = YES;// 禁止键盘出现时的界面滚动
//    [self hideKeyBoard];
//    [_inputfield resignFirstResponder];
    
}


@end
